package com.chee.plant.hibernate.dao;

import java.util.Calendar;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.chee.plant.hibernate.object.Email;
import com.chee.plant.hibernate.object.User;
import com.chee.plant.server.HibernateSessionFactory;

/**
 * 对应Email数据库访问操作  
 * @author xue cb 
 *
 */
public class EmailDAO {

	/**
	 * 获取全部用户站内信
	 * 
	 * @return 用户站内信集合
	 */
	@SuppressWarnings("unchecked")
	public List<Email> getAllEmail() {
		Session session = HibernateSessionFactory.getSession();
		String hql = "select email from Email as email";
		Query query = session.createQuery(hql);
		return query.list();
	}

	/**
	 * 根据用户Id返回用户的站内信
	 * 
	 * @param userId
	 *            用户Id
	 * @return 指定用户的所有站内信集合
	 */
	@SuppressWarnings("unchecked")
	public List<Email> getEmailByUserId(Integer userId) {
		Session session = HibernateSessionFactory.getSession();
		String hql = "select email from Email as email where email.OwnerId=:ownerId";
		Query query = session.createQuery(hql);
		query.setInteger("ownerId", userId);
		return query.list();
	}

	/**
	 * 给所有用户群发邮件
	 * 
	 * 
	 * @param title
	 *            邮件标题
	 * @param content
	 *            邮件内容
	 */
	public void saveEmails(String title, String content) {

		// 获取所有用户信息：id name
		List<User> list = new UserDAO().getAllUser();
		// 获取所有用户数量
		int count = list.size();
		// 循环为每个用户插入数据
		for (int i = 0; i < count; i++) {
			// 获取session
			Session session = HibernateSessionFactory.getSession();
			Transaction transaction = null;
			try {
				// 开启一个事务
				transaction = session.beginTransaction();
				// 开始向数据库中插入数据

				Email email = new Email();
				email.setContent(content);
				email.setCreated(Calendar.getInstance().getTime());
				email.setFromId("管理员");
				// 获取用户Id
				int userId = ((User) (list.get(i))).getId();
				email.setOwnerId(userId);
				email.setTittle(title);

				// 获取用户姓名
				String userName = ((User) (list.get(i))).getName();
				email.setToId(userName);
				session.save(email);
				// 提交事务
				transaction.commit();

			} catch (Exception e) {
				if (null != transaction) {
					transaction.rollback();
				}
				e.printStackTrace();

			} finally {
				// 关闭session
				session.close();
			}
		}

	}

	/**
	 * 主方法，用于测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// 1， 测试getEmailByUserId(Integer userId)
		List<Email> list = new EmailDAO().getEmailByUserId(2);
		for (int i = 0; i < list.size(); i++) {
			System.out.println(((Email) (list.get(i))).getContent());
		}

		// 2， 测试getAllEmail
		List<Email> li = new EmailDAO().getAllEmail();
		System.out.println(li.size());

		for (int i = 0; i < li.size(); i++) {
			Email email = (Email) (li.get(i));

			System.out.println("  *" + email.getId() + "  *"
					+ email.getOwnerId() + "  *" + email.getFromId() + "  *"
					+ email.getToId() + "  *" + email.getTittle() + "  *"
					+ email.getContent() + "  *" + email.getCreated());
		}

		// 3, 测试saveEmails(String title, String content)

		EmailDAO sfo = new EmailDAO();
		sfo.saveEmails("test again", "This is a test!");

	}

}
